package fr.cephb.operonj.tools.cmdline.remapper;

import com.sleepycat.bind.tuple.StringBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;

import fr.cephb.operonj.core.bio.ChromRange;
import fr.cephb.operonj.core.db.binding.ChromRangeBinding;
import fr.cephb.operonj.core.je.DuplicateDB;

public class SNPToPositionDB
	extends DuplicateDB<String, ChromRange>
	{
	private int buildId;
	private StringBinding keyBinding=new StringBinding();
	private ChromRangeBinding valueBinding=new ChromRangeBinding();
	private static final String DEFAULT_NAME="snp2position_build_";
	public SNPToPositionDB(Environment env, Transaction txn,
			int buildId,
			DatabaseConfig dbConfig) throws DatabaseException
		{
		super(env, txn, DEFAULT_NAME+buildId, defaultDbCfg(env,dbConfig));
		this.buildId=buildId;
		}
	
	public int getBuildId()
		{
		return buildId;
		}
	
	@Override
	public String getDefaultName()
		{
		return DEFAULT_NAME+getBuildId();
		}

	@Override
	public TupleBinding<String> getKeyBinding()
		{
		return keyBinding;
		}

	@Override
	public TupleBinding<ChromRange> getValueBinding()
		{
		return valueBinding;
		}
	
	public static int chromToIndex(String chrom)
		{
		chrom=chrom.toLowerCase().trim();
		if(chrom.startsWith("chrom")) chrom=chrom.substring(5);
		else if(chrom.startsWith("chr")) chrom=chrom.substring(3);
		else if(chrom.startsWith("k")) chrom=chrom.substring(1);
		if(chrom.equals("x")) return 23;
		else if(chrom.equals("y")) return 24;
		else if(chrom.equals("m")) return 25;
		try
			{
			return Integer.parseInt(chrom);
			}
		catch (Exception e)
			{
			throw new IllegalArgumentException("bad chrom:"+chrom);
			}
		}
	
	public OperationStatus add(Transaction txn,String name,String chrom,int start,int end)
		throws DatabaseException
		{
		int chromId= chromToIndex(chrom);
		ChromRange cp=new ChromRange(chromId, start,end);
		OperationStatus status=getDatabase().putNoDupData(txn,
				keyToEntry(name),
				valueToEntry(cp)
				);
		if(status!=OperationStatus.SUCCESS)
			{
			if(status==OperationStatus.KEYEXIST)
				{
				LOG.warning("Duplicate entry "+name+" "+cp);
				}
			else
				{
				LOG.warning("Error on input "+name+" "+cp+" "+status);
				}
			}
		return status;
		}
	
	}
